{% extends '_base.html' %}

{% block content %}

<div style="padding: 15px;">
	<div style="text-align:left">
		<fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
			<legend>{{ title }}</legend>
		</fieldset>
	</div>

	<div class="layui-upload">
		<div style="text-align:center">
			<span style="padding: 0 5px">
				<button type="button" class="layui-btn" id="record_button">开始录音</button>
			</span>
			<span style="padding: 0 5px">
				<button type="button" class="layui-btn" id="upload_button">上传检测</button>
			</span>
			<span style="padding: 0 5px">
				<button type="button" class="layui-btn layui-btn-normal" href="#" onclick="download_table_as_csv('result_table');">保存检测结果</button>
			</span>
		</div>
		<br>
 
		<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="upload_progress">
			<div class="layui-progress-bar layui-bg-green" lay-percent="0%"></div>
		</div>

		<div class="layui-upload-list">
			<table class="layui-table" id="result_table">
				<thead>
					<tr>
						<th>文件名</th>
						<th>大小</th>
						<th>状态</th>
						<th>得分</th>
						<th>检测结果</th>
						<th>播放音频</th>
					</tr>
				</thead>
				<tbody id="demoList"></tbody>
			</table>
		</div>
	</div>

</div>
{% endblock %}

{% block script %}
<script src="/static/js/opus-recorder-v8.0.3/recorder.min.js"></script>
<script>
	
	let is_recording = false;
	function set_recording_status(status) {
		if (status) {
			is_recording = true
			$('#record_button').html("录音中...点击结束录音")
		} else {
			is_recording = false
			$('#record_button').html("开始录音")
		}
	}
	function disable_recording() {
		$('#record_button').html("当前浏览器不支持录音");
		$('#record_button').attr("disabled", true);
		$('#record_button').addClass("layui-btn-disabled");
	}

	function init() {
		if (!Recorder.isRecordingSupported()) {
			disable_recording();
			return;
		}
		var recorder = new Recorder({
			monitorGain: 0,
			recordingGain: 1,
			numberOfChannels: 1,
			wavBitDepth: 16,
			encoderPath: "/static/js/opus-recorder-v8.0.3/waveWorker.min.js"
		});

		$('#record_button')[0].addEventListener("click", function () {
			if (is_recording) {
				recorder.stop(); 
			} else {
				recorder.start().catch(function (e) {
					console.log(e)
					set_recording_status(false)
					alert('错误：' + e.message);
				});
			}
		});

		recorder.onstart = function () {
			set_recording_status(true)
			console.log('Recorder is started');
		};

		recorder.onstop = function () {
			set_recording_status(false)
			console.log('Recorder is stopped');
		};

		recorder.onpause = function () {
			set_recording_status(false)
			console.log('Recorder is paused');
		};

		recorder.onresume = function () {
			set_recording_status(true)
			console.log('Recorder is resuming');
		};

		recorder.onstreamerror = function (e) {
			set_recording_status(false)
			console.log('Error encountered: ' + e.message);
		};

		recorder.ondataavailable = function (typedArray) {
			var dataBlob = new Blob([typedArray], { type: 'audio/wav' });
			var fileName = new Date().toISOString() + ".wav";
			// var url = URL.createObjectURL(dataBlob);

			let formData = new FormData();
			const file = new File([dataBlob], fileName)
			formData.append("file", file);
			formData.append("csrfmiddlewaretoken", '{{ csrf_token }}');

			fetch('', { method: "POST", body: formData })
				.then(function (response) {
					console.log('HTTP response code:', response.status);

					response.json().then(function (res) {
						console.log(res)
						if (res.upload_status == "success") { //上传成功
							let preview = 'no-preview';
							const ext = res.file_path.substr(res.file_path.lastIndexOf(".") + 1);
							if (ext == 'mp4') {
								preview = "<video width=\"320\" height=\"240\" preload controls><source src=\"" + res.file_path + "\"></video>"
							} else {
								preview = "<audio controls><source src=\"" + res.file_path + "\"></audio>"
							}
							const tr = $([
								'<tr>',
								'<td>' + file.name + '</td>',
								'<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
								'<td><span style="color: #5FB878;">上传成功</span></td>',
								'<td>' + res.score + '</td>',
								'<td>' + '<span style="color: #FF5722;">' + res.audio_type + '</span>' + '</td>',
								'<td>' + preview + '</td>',
								'</tr>'
							].join(''))

							$('#demoList').prepend(tr);
						}
					})
				})
				.catch(function (reason) {
					console.log('Huston we have problem...:', reason);
				})
		}
	};
	init()
</script>

<script>
	$('#a').on('click', function () {
		console.log("hi");
		layer.open({
			type: 1,
			area: ['600px', '360px'],
			shadeClose: true, //点击遮罩关闭
			content: '\<\div style="padding:20px;">hi\<\/div>'
		});
	});

	layui.use(['element', 'upload'], function () {
		var $ = layui.jquery
		var upload = layui.upload;
		var element = layui.element;

		var n_total_file = 0;
		var n_processed_file = 0;
		var n_processing_file = 0;

		var demoListView = $('#demoList')
		var uploadListIns = upload.render({
			elem: '#upload_button',
			url: '',
			accept: 'file',
			// ansyn: false, //开启同步请求
			multiple: true,
			auto: false,
			exts: 'wav|mp3|flac|wma|mp4|mov|flv|rmvb',
			data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
			bindAction: '#testListAction',
			choose: function (obj) {
				var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列

				n_total_file = Object.keys(files).length;
				n_processed_file = 0;
				n_processing_file = 0;

				//读取本地文件
				obj.preview(function (index, file, result) {
					var tr = $([
						'<tr id="upload-' + index + '">',
						'<td>' + file.name + '</td>',
						'<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
						'<td>等待上传</td>',
						'<td>-</td>',
						'<td>-</td>',
						'<td>-</td>',
						'</tr>'
					].join(''))
					demoListView.prepend(tr);
					function do_upload(obj, index, file) {
						if (n_processing_file > 10) {
							setTimeout(do_upload, 500, obj, index, file)
							return
						}
						obj.upload(index, file);
						n_processing_file += 1;
					}
					setTimeout(do_upload, 500, obj, index, file); // 延迟上传
				});
			},
			before: function (obj) {

			},
			done: function (res, index, upload) {
				// console.log("upload status is " + res.upload_status);
				if (res.upload_status == "success") { //上传成功
					var tr = demoListView.find('tr#upload-' + index)
					var tds = tr.children();
					tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
					tds.eq(3).html(res.score);
					tds.eq(4).html('<span style="color: #FF5722;">' + res.audio_type + '</span>');
					var ext = res.file_path.substr(res.file_path.lastIndexOf(".") + 1);
					if (n_processed_file < 100) {
						if (ext == 'mp4') {
							tds.eq(5).html("<video width=\"320\" height=\"240\" preload controls><source src=\"" + res.file_path + "\"></video>")
						} else {
							tds.eq(5).html("<audio controls><source src=\"" + res.file_path + "\"></audio>")
						}
					} else {
						tds.eq(5).html("<文件数量过多，暂停展示>")
					}
					n_processed_file += 1;
					n_processing_file -= 1;
					element.progress('upload_progress', parseInt(n_processed_file / n_total_file * 100) + '%')
					return delete this.files[index]; //删除文件队列已经上传成功的文件
				}
				this.error(index, upload);
			},
			error: function (index, upload) {
				console.log("error index is " + index);
				var tr = demoListView.find('tr#upload-' + index)
				var tds = tr.children();
				tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
				tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
			}
		});
	});
</script>

<script>
	// Quick and simple export target #table_id into a csv
	function download_table_as_csv(table_id, separator = ',') {
		// Select rows from table_id
		var rows = document.querySelectorAll('table#' + table_id + ' tr');
		// Construct csv
		var csv = [];
		for (var i = 0; i < rows.length; i++) {
			var row = [], cols = rows[i].querySelectorAll('td, th');
			for (var j = 0; j < cols.length; j++) {
				// Clean innertext to remove multiple spaces and jumpline (break csv)
				var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
				// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
				data = data.replace(/"/g, '""');
				// Push escaped string
				row.push('"' + data + '"');
			}
			csv.push(row.join(separator));
		}
		var csv_string = csv.join('\n');
		// Download it
		var filename = '检测结果' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
		var link = document.createElement('a');
		link.style.display = 'none';
		link.setAttribute('target', '_blank');
		link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
		link.setAttribute('download', filename);
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	}
</script>
{% endblock %}